package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"rbook/api/request"
	"rbook/globals"
	"rbook/intermal/model"
	"time"
)

func ContentList(c *gin.Context) {
	param := request.ContentList{}
	if err := c.ShouldBind(&param); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 400,
			"mes":  "参数错误",
		})
		return
	}
	var data []model.Content
	page := param.Page
	if page <= 0 {
		page = 1
	}

	pageSize := param.PageSize
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize
	globals.DB.Offset(int(offset)).Limit(int(pageSize)).Where("title like ?", "%"+param.Title+"%").Find(&data)

	result, err := globals.RDB.Get(globals.Ctx, "content_list").Result()
	if result != "" {
		err = json.Unmarshal([]byte(result), &data)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"mes": "序列化失败",
			})
		}
	} else {
		marshal, _ := json.Marshal(&data)
		globals.RDB.Set(globals.Ctx, "content_list", marshal, time.Hour*1)
	}

	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 400,
			"mes":  "内容展示失败",
			"data": data,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"mes":  "内容展示成功",
		"data": data,
	})

}

func ContentDetails(c *gin.Context) {
	param := request.ContentDetails{}
	if err := c.ShouldBind(&param); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 400,
			"mes":  "参数错误",
		})
		return
	}
	data := model.Content{
		Id: param.Id,
	}
	//判断互动消息是否点赞
	var inter bool
	var in model.Interaction
	if in.Type != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 400,
			"mes":  "已收藏",
		})
		return
	}

	err := globals.DB.Model(model.Content{}).Where("id=?", param.Id).First(&data).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 400,
			"mes":  "内容详情展示失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"mes":  "内容详情展示成功",
		"data": map[string]interface{}{
			"contentcount": data.ViewCount,
			"inter":        inter,
			"data":         data,
		},
	})
}
